package com.hm.shopping.web.common;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.hm.common.oss.qiniu.su.QiNiuHandlerSupport;
import com.hm.common.util.FileUtil;
import com.hm.shopping.auto.SystemEnvConfigProperties;
import com.hm.shopping.auto.su.BaseController;
import com.hm.shopping.auto.su.R.Uri;
import com.qiniu.util.Auth;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 2018年1月27日 下午12:41:31
 * @version 1.0
 * @describe
 */
@Slf4j
@Controller
@RequestMapping(Uri.PC + "/common")
public class CommonController extends BaseController {

	@Autowired
	private QiNiuHandlerSupport qiNiuHandlerSupport;

	@Autowired
	private SystemEnvConfigProperties systemEnvConfigProperties;

	@RequestMapping(value = "/uploadFile.do", method = RequestMethod.POST)
	public void uploadFile(@RequestParam("file") MultipartFile file) {
		try {
			String filename = file.getOriginalFilename();
			String suffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
			File tempFile = File.createTempFile(filename, suffix);
			tempFile.deleteOnExit();
			file.transferTo(tempFile);
			byte[] datas = FileUtil.getFile(tempFile);
			String uploadFileUri = qiNiuHandlerSupport.buildSampleHandler().upload(System.nanoTime() + "." + suffix, datas);
			super.successful(uploadFileUri);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			super.failure(e.getMessage());
		}
	}

	@RequestMapping(value = "uploadFileToken.do", method = RequestMethod.POST)
	public void uploadFileToken() {
		try {
			Auth auth = Auth.create(systemEnvConfigProperties.getQiniu().getAccessKey(), systemEnvConfigProperties.getQiniu().getSecretKey());
			String upToken = auth.uploadToken(systemEnvConfigProperties.getQiniu().getBucket());
			super.successful(upToken);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			super.failure(e.getMessage());
		}
	}
}
